package com.core.service.User;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.mapper.ReservationMapper;
import com.core.mapper.UserMapper;
import com.core.pojo.Result.PageResult;
import com.core.pojo.Result.Result;
import com.core.pojo.SeatReservation.entity.Reservation;
import com.core.pojo.User.entity.User;
import com.core.pojo.User.entity.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.core.constant.RedisConstants.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class UserInfoServiceImpl implements UserInfoService{
    private final UserMapper userMapper;
    private final UserLoginService userLoginService;
    private final ReservationMapper reservationMapper;
    private final StringRedisTemplate stringRedisTemplate;

    /**
     * 修改学生信息
     * @param user
     * @return
     */
    @Override
    public Result updateUserInfo(User user) {
        // 检查用户信息是否合理
        Result authenticate=userLoginService.userAuthenticate(user);
        if(authenticate.getCode()!=1){
            return authenticate;
        }
        if(user.getCreateTime()==null){
            user.setCreateTime(userLoginService.queryUserById(user.getId()).getCreateTime());
        }
        userMapper.updateById(user);
        // 把更新后的用户信息写入缓存
        String tokenKey=LOGIN_USER_KEY+user.getId();
        Map<String, Object> cacheMap = BeanUtil.beanToMap(
                user,
                new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((f,v) -> v.toString())
        );
        stringRedisTemplate.opsForHash().putAll(tokenKey, cacheMap);
        // 设置缓存时间
        stringRedisTemplate.expire(tokenKey,LOGIN_USER_TTL, LOGIN_USER_TIMEUNIT);

        return Result.success();
    }

    /**
     * 获取该用户预约记录（分页）
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Result<PageResult<Reservation>> queryUserReservations(int page, int pageSize) {
        // 1. 获取当前用户ID
        Long userId= UserContext.getUserId();

        if (userId == null) {
            // 根据你的业务逻辑处理用户未登录的情况
            return Result.error("用户未登录");
        }

        // 2. 启动 PageHelper 分页
        PageHelper.startPage(page, pageSize);

        // 3. 执行查询
        LambdaQueryWrapper<Reservation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Reservation::getUserId, userId); // 假设 Reservation 实体有 userId 字段
        queryWrapper.orderByAsc(Reservation::getCreateTime); // 按创建时间降序排序
        List<Reservation> reservationList = reservationMapper.selectList(queryWrapper);

        // 4. 使用 PageInfo 包装查询结果，以获取详细的分页信息
        PageInfo<Reservation> pageInfo = new PageInfo<>(reservationList);

        // 5. 封装成自定义的 PageResult 对象
        PageResult<Reservation> pageResult = PageResult.fromPageInfo(pageInfo);

        // 6. 返回成功结果
        return Result.success(pageResult);

    }
}
